<template>
  <massif-layout leftWidth="300px" :showBack="false" @back="goBack">
    <template v-slot:left>
      <div v-if="!eidtMinRowType">
      <div class="receive-land-left-view">
        <div class="header-view">
                    <div class="title">认领地块</div>
                    <vxe-button 
                        type="text" 
                        size="small" 
                         @click="btnDelAll"
                        status="danger" 
                        icon="vxe-icon-delete-fill">全部删除</vxe-button>
                </div>
        <landTotal :farmcount="farmcount" />
        <div class="optate-search">
              <div class="scinput">
                  <el-input placeholder="请输入地块名称" clearable size="mini" v-model="searchInfo.farmLandName">
                      <template #append style="padding: 0 4px;">
                      <vxe-button type="text" @click="btnQuery" icon="vxe-icon-search"></vxe-button>
                      </template>
                  </el-input>
              </div>
          </div>
        <querySelect @change="querySelectFilter" />
        <LandList :tableData="tableData"
                  height="calc(100vh - 370px)"
                  :page-info="searchInfo"
                  showDelete
                  @onClick="setMapData"
                  @onDelete="btnDel"
                  @page-change="toPage" />
      </div>
    </div>
        <!--地块编辑-->
        <div v-else>
          <eidtRow   :farmLandId="landInfo?.farmLandId"  @close="eidtMinRowType=false" />
        </div>
    </template>
    <MapViewer 
        ref="refreceiveLandMap"
        :location="locationMap" 
        @onInit="initMap" 
        @onDrag="changePostion"
        @onDragEnd="onDragEndPostion"
        @onZoom="onChangeZoom"
        @onZoomEnd="onDragEndPostion"
         domId="receive-land-Id" />

    <PoiPopup v-if="showPop"  :popOption="popObjct" @click="clickLand"   @onClose="showPop=false" />
    <vxe-button  class="back-view" v-if="!eidtMinRowType" size="small" @click="goBack" content="返回" icon="vxe-icon-arrow-left"></vxe-button>
    <div class="bottom-view-tips">
       <div style="background-color: rgb(43, 129, 212, 1);border:1px solid rgb(43, 129, 212, 1);">待认领</div>
       <div style="background-color: #25c289;border:1px solid #25c289;">已认领</div>
       <div>被认领</div>
    </div>

    <div class="land-detail" v-if="showDetail">
          <land-detail  
                  :farmLandId="landInfo?.farmLandId" 
                  @clickDel="btnDel"
                  @eidt="eidtClick"
                  :farmLandNo="dropFarmLandNo"
                  :farmLandPic="dropFarmLandPic" 
                  @close="showDetail=false" />
    </div>
  </massif-layout>
</template>

<script setup>
// 这里的name是为了做页面缓存，其值要跟路由里面的name值一样
import {ref,onMounted} from 'vue'
import {getFarmCount, releaseFarmland, claimLand, uploadFile,getCompositeFarmland, tancLand} from '@/api/gis'
import {flattenArrayList,uniqArray} from '@/utils/common'
import {getLandList} from '@/api/plant'
import massifLayout from '../../components/layout.vue'
import {useUserStore} from '@/pinia/modules/user'
import landDetail from './landDetail.vue'
import eidtRow from './eidtRow.vue'
import MapViewer from "@/components/gisMapBox/index.vue";
import PoiPopup from '@/components/gisMapBox/components/PoiPopup.vue';
import {VXETable} from 'vxe-table'
import landTotal from '../components/landTotal.vue'
import LandList from '../components/landList.vue'
import querySelect from '../components/querySelect.vue'

const emit = defineEmits(['close', 'eidt'])
const props = defineProps({
      farmcount:{
        type:Object,
        default:{farmLandTotal:0,farmLandCount:0}
      },
      mapList:{
        type:Array,
        default:[]
      }
  }) 

const userStore = useUserStore()
const page = ref(1)
const dropFarmLandId = ref('') // 下拉选择地块id
const dropFarmLandNo = ref('') // 下拉选择地块id
const dropFarmLandPic = ref('')
const tableData = ref([])
const farmcount = ref({farmLandTotal: 0, farmLandCount: 0})
const showDetail = ref(false)
const showPop = ref(false)
const openDetails = ref(false)
const eidtMinRowType = ref(false)
const searchInfo = ref({page: 1, limit: 10,total: 0})
const refreceiveLandMap =ref(null)
const locationMap = ref({})
const popObjct = ref({})
const landInfo = ref({})
const mapLandList = ref([])
const dataList = ref([])
const loadingLand = ref(true)
let mapView=null
let farmLandId = null
onMounted(() => {
   VXETable.modal.message({content: '点击地块认领', status: 'warning', duration: 5000})
   VXETable.modal.message({content: '如自己地块被其他农场认领可申述', status: 'warning', duration: 10000})
   btnQuery()
})

const btnQuery = () => {
        searchInfo.value.page = 1
        get_land_list()
        get_farm_count()
}
const querySelectFilter = (data) => {
        searchInfo.value = {...searchInfo.value,...data}
        btnQuery()
}


//地块统计
const get_farm_count = () => {
  getFarmCount({
    ...searchInfo.value,
        landTagId:searchInfo.value.landTagId?[searchInfo.value.landTagId]:undefined,
        landSource:2,
        farmId:userStore.userInfo.farmId
  }).then(res => {
    if (res.success) {
      farmcount.value = res.data
    }
  })
}

//已认领列表
const get_land_list = async () => {
  const res = await getLandList({
    ...searchInfo.value,
        landTagId:searchInfo.value.landTagId?[searchInfo.value.landTagId]:undefined,
        landSource:2,
        farmId:userStore.userInfo.farmId
  })
  if (res.success) {
     tableData.value = res.data
     searchInfo.value.total = res.total
  }
}

const initMap =async (map)=>{
     mapView = map
     dataList.value= props.mapList
     addLandList()
}

const onDragEndPostion =async (e)=>{
  let point = mapView.getCenter();
  let currentZoom = mapView.getZoom();
  if(currentZoom<12 || !loadingLand.value){
    return false
  }
  loadingLand.value = false
    let res = await getCompositeFarmland({
      landSource:2,
      radius:(6000/currentZoom)>500?500:(5000/currentZoom),
      lng:point.lng,
      lat:point.lat
    })
    if(res.success){
      loadingLand.value = true
      dataList.value = uniqArray(dataList.value.concat(res.data||[]).filter((item)=>item.geom!=null),'farmLandId')
      updateData()
    }
}
const updateData =()=>{
    let filterList =dataList.value.map((item)=> {
            return {
                type: 'Feature',
                id:item.farmLandId,
                properties: {
                    description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                    // lineColor:'#25c289',
                    lineColor:(item.farmId!=0 &&item.farmId !=userStore.userInfo.farmId)?'#fdd143':(item.farmId==userStore.userInfo.farmId?'#25c289':'#2b81d4'),
                    lineWidth:3,
                    ...item
                },
                geometry: {
                    type: 'Polygon',
                    coordinates: [JSON.parse(item.geom||'[]')]
                }
            }
    })
    mapView.getSource('polygons-source-receive').setData({type: 'FeatureCollection', features:filterList})
}

const addSourceData =()=>{
         mapView.addSource('polygons-source-receive', {
            type: 'geojson',
            data: {
                type: 'FeatureCollection',
                features: dataList.value.map((item)=> {
                  if(item?.geom && item.geom!='null' && item.geom !=null){
                    return {
                        type: 'Feature',
                        id:item.farmLandId,
                        properties: {
                            description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                            // lineColor:'#25c289',
                            lineColor:(item.farmId!=0 &&item.farmId !=userStore.userInfo.farmId)?'#fdd143':(item.farmId==userStore.userInfo.farmId?'#25c289':'#2b81d4'),
                            lineWidth:3,
                            ...item
                        },
                        geometry: {
                            type: 'Polygon',
                            coordinates: [JSON.parse(item.geom||'[]')]
                        }
                    }
                  }
                })
            }
    })
}

const addLandList =()=>{
       addSourceData()
       //添加线条
       mapView.addLayer({
            'id': 'polygons-layer-line-receive',
            'type': 'line',
            'source': 'polygons-source-receive',
            'layout': {},
            'paint': {
                'line-color': ['get', 'lineColor'],
                'line-width': ['get', 'lineWidth']
            }
    })

    // 添加多边形图层-图层
    mapView.addLayer({
            'id': 'polygons-layer-fill-receive',
            'type': 'fill',
            'source': 'polygons-source-receive',
            'paint': {
            'fill-opacity': 0.5,
              'fill-color': [
                'case',
                ['boolean', ['feature-state', 'click'], false],
                '#59e3b1',
                'rgba(255, 255, 255, 0)']
              },
              "interactive": true
        })

        // 添加多边形图层-文字
        mapView.addLayer({
            'id': 'polygons-layer-text-receive',
            'type': 'symbol',
            'source': 'polygons-source-receive',
            layout: {
                'text-field': ['get', 'description'],
                'text-size': 13,
                'text-anchor': 'center',
                'visibility': 'none',
                'text-offset': [0, 1.5],
                "text-translate": [0, 1],
                "text-translate-anchor": "map",
                'text-offset': [0, 1.5],
            },
            paint: {
                'text-color': '#ffffff',
                "text-halo-color": "#000000",
                 "text-halo-width": 1 
            },
            metadata: {
                'renderedOnServer': false
            }
        });
    

     mapView.on('click','polygons-layer-fill-receive',(e)=> {
        let item = e.features[0]?.properties
        landInfo.value = {
          ...item,
          // longitude:Number(item.locationLongitude),
          // latitude:Number(item.locationLatitude)
          longitude:e.lngLat.lng,
          latitude:e.lngLat.lat
        }
        changePostion()
        showPop.value = true
        changeLandColors(item.farmLandId)

      })

    //  mapView.on('mouseenter', 'polygons-layer-fill-receive',(e)=> {
    //       mapView.setLayoutProperty('polygons-layer-text-receive', 'visibility', 'visible');
    // })
    
    //  mapView.on('mouseleave', 'polygons-layer-fill-receive', (e)=> {
    //       mapView.setLayoutProperty('polygons-layer-text-receive', 'visibility', 'none');
    // })
}

const eidtClick = (data) => {
  showDetail.value = false
  openDetails.value = false
  dropFarmLandId.value = data.farmLandId
  eidtMinRowType.value = true
  removePostion()
}

const changeLandColors =(Id)=>{
    if(farmLandId){
            mapView.setFeatureState({source: 'polygons-source-receive', id:farmLandId },{ click: false });
        }
    farmLandId=Id
    mapView.setFeatureState({source: 'polygons-source-receive', id: Id },{ click: true });
}

const setMapData = (row) => {
    landInfo.value = row
    locationMap.value={
      longitude:Number(row.locationLongitude),
      latitude:Number(row.locationLatitude)
    }
    // showPop.value = true
    changePostion()
    changeLandColors(row.farmLandId)
}

const changePostion = () => {
  let item = landInfo.value
  const point = refreceiveLandMap.value.getWindXY(Number(landInfo.value.longitude),Number(landInfo.value.latitude))
    const popOption = {
            ...item,
            title:item.farmName||item.farmLandNo,
            farmId:item.farmId,
            companyId:item.companyId,
            farmLandId:item.farmLandId,
            pic:item.pic,
            screenX: point.left,
            screenY: point.top+50,
            visible:true,
            mapX: item.longitude,
            mapY: item.latitude,
            btnText:'地块详情',
            values: [
                {
                    label: '所属农场',
                    value: item.farmName
                },
                {
                    label: '地块编号',
                    value: item.farmLandNo
                },
                {
                    label: '地块名称',
                    value: item.farmLandName
                },
                {
                    label: '地块面积',
                    value:  Number(item.mapAreaSize||0).toFixed(2)+'亩'
                },
                {
                    label: '位置',
                    value: item.locationAddress
                }
            ],
            footerList:[
                {
                    btnText:(item.farmId!=0 &&item.farmId !=userStore.userInfo.farmId)?'申诉地块归属':(item.farmId==userStore.userInfo.farmId?'已认领':'点击认领'),
                    icon:(item.farmId!=0 &&item.farmId !=userStore.userInfo.farmId)?'vxe-icon-feedback':(item.farmId==userStore.userInfo.farmId?'vxe-icon-check':'vxe-icon-send'),
                    farmId:item.farmId,
                    color:item.farmId?'#25c289':'#409eff',
                    farmLandId:item.farmLandId,
                    type:(item.farmId!=0 &&item.farmId !=userStore.userInfo.farmId)?2:(item.farmId==userStore.userInfo.farmId?0:1),

                },
                {
                    btnText:'地块详情',
                    icon:'vxe-icon-maximize',
                    farmId:item.farmId,
                    color:'#25c289',
                    farmLandId:item.farmLandId,
                    type:3
                }
            ]
  }
    popObjct.value = popOption
}

const onChangeZoom =(row)=>{

   if(row.currentZoom<15){
        showPop.value = false
        mapView.setLayoutProperty('polygons-layer-text-receive', 'visibility', 'none');
    }else{
      mapView.setLayoutProperty('polygons-layer-text-receive', 'visibility', 'visible');
    }
 changePostion()
}

const removePostion = () => {
    showPop.value = false
}

const toPage = (pageNum) => {
  page.value = pageNum
  get_land_list()
}

const goBack = () => {
  emit('close')
}
const goDetail = (row)=>{
    dropFarmLandId.value = row.farmLandId
    dropFarmLandPic.value = row.pic
    showDetail.value = true
  }
  //认领地块
  const clickLand =async (row)=>{
    switch (row.type) {  
    case 1:  
     if(row.pic){
            goEditFarmLand(row)
        }else{
            VXETable.modal.message({id: 'loading-msg', content: '正在认领...', status: 'loading',duration:-1 })
            goEditFarmLand(row)
        }
        break;  
        case 2:  
        const info = await VXETable.modal.confirm({
                confirmButtonText:'确认申诉',
                title:'提示',
                content:'该地块已被其他农场认领，是否申述？\n申述处理时间1-3工作日，请耐心等待。'})
                if(info==='confirm'){
                    let res = await claimLand({
                        "applicant":userStore.userInfo.nickName,
                        "applicantFarmId":userStore.userInfo.farmId,
                        "applicantFarmName": userStore.userInfo.FarmName,
                        "disputedFarmId": row.farmId,
                        "disputedFarmName": row.farmName,
                        "disputedParcelLandId":  row.farmLandId,
                        "disputedParcelLocation": row.locationAddress
                    })
                    if(res.success){
                        VXETable.modal.message({ content: '申诉成功', status: 'success'})
                    }else{
                        VXETable.modal.message({ content: res.message, status: 'error'})
                    }
                }
            break;  
        case 3:
        goDetail(row)
        break;
    }
  }
const btnDelAll = () => {
  btnDel(tableData.value.map((item) => item.farmLandId), 'all')
}

//移除地块
const btnDel = async (row, type) => {
  const info = await VXETable.modal.confirm({
    title: '确认删除认领的地块吗？',
    content: '删除后认领的地块不可见。'
  })
  if (info === 'confirm') {
    let res = await releaseFarmland(type == 'all' ? row : [row.farmLandId])
    if (res.success) {
      VXETable.modal.message({content: '删除成功', status: 'success'})
      showDetail.value = false
      changeLandColor(2,row.farmLandId)
    } else {
      VXETable.modal.message({content: res.message, status: 'error'})
    }
  }
}

const changeLandColor =(type,farmLandId)=>{
  //type 1添加 2去掉
  removePostion()
  btnQuery()
  let index = dataList.value.findIndex(item => item.farmLandId ==farmLandId);
  if(type==1){
    dataList.value[index].farmId =userStore.userInfo.farmId
  }else{
    dataList.value[index].farmId =0
  }
  updateData()
}

const goEditFarmLand = async (row) => {
  let res = await tancLand({
    farmId: userStore.userInfo.farmId,
    farmLandId: row.farmLandId,
    serialno: row.serialno
    // picSource: row.picSource,
    // pic: row.pic
  })
  if (res.success) {
    VXETable.modal.close('loading-msg')
    VXETable.modal.message({content: '认领成功', status: 'success'})
    popObjct.value={
      ...popObjct.value,
      farmId: userStore.userInfo.farmId
    }
    changeLandColor(1,row.farmLandId)
  } else {
    VXETable.modal.message({content: res.message, status: 'error'})
  }
}

</script>

<style lang="scss" scoped>
.receive-land-left-view {
  box-sizing: border-box;
  display: flex;
  flex-flow: column;
  height: calc(100vh - 105px);
  padding:0;
  //overflow: hidden;
  .optate-search {
            display: flex;
            padding: 0 10px;
            margin: 0 0 5px 0;

            .scinput {
                flex: 1;
            }
    }
  .header-view{
            display: flex;
            justify-content: space-between;
            height: 40px;
            line-height: 40px;
            padding: 0 10px;
            position: relative;
            .title{
                font-size: 15px;
                color: #333;
                font-weight: bold;
                text-indent:10px;
                &::before {
                    content: "";
                    height: 16px;
                    width: 4px;
                    background-color: #FF9C00;
                    margin: 0;
                    position: absolute;
                    top: 10px;
                    left: 10px;
               }
            }
    
  }

}

.btn-view {
  display: flex;
  justify-content: space-between;

  .btn {
    width: 100%;
    border-top: 1px solid #eee;
    padding-top: 15px;
    font-size: 15px;
  }
}

.back-view{
    position: absolute;
    right:10px;
    top:10px;
    z-index:999;
  }
.land-detail {
  position: absolute;
  z-index: 2005;
  width: auto;
  height: auto;
  left: 330px;
  top: 10px;
  bottom: 10px;
  right: 10px;
  background-color: #fff;
}

.bottom-view-tips {
  position: absolute;
  z-index: 99;
  bottom: 10px;
  left: 320px;
  display: flex;
  justify-content: flex-start;
  > div {
    height: 30px;
    width: 80px;
    text-align: center;
    font-size: 14px;
    line-height: 30px;
    background-color: rgb(253, 209, 67);
    border: 1px solid rgb(253, 209, 67);
    color: #fff;
    border-radius: 2px;
    margin-right: 4px;
  }
}
</style>
  